import React, { Component } from "react";
//受控组件
export default class FormComSimple extends Component {
  //1. 声明状态
  state = {
    user: "",
    pass: "",
    email: ''
  };


  //简化受控的操作  save('user')  save('pass')
  save = (type) => {
    return (e) => {
      this.setState({
        [type]: e.target.value,
      });
    };
  };

  //登录的事件回调
  login = (e) => {
    //阻止默认行为
    e.preventDefault();
    //输出用户名和密码
    console.log(`用户名: ${this.state.user}  密码: ${this.state.pass}`);
  };

  //重置的事件回调
  reset = (e) => {
    //阻止默认行为
    e.preventDefault();
    //清空表单元素的值
    this.setState({
      user: "",
      pass: "",
    });
  };

  render() {
    return (
      <div>
        <h2>登录</h2>
        <hr />
        <form action="">
          {/* 2. 使用状态值, 设置 input 元素的 value 值   input 是受控, 受状态控制的 */}
          用户名:{" "}
          <input
            type="text"
            name="username"
            value={this.state.user}
            onChange={this.save("user")}
          />
          <br></br>
          密码:{" "}
          <input
            type="password"
            name="password"
            value={this.state.pass}
            onChange={this.save("pass")}
          />
          <br />
          邮箱:{" "}
          <input
            type="text"
            name="email"
            value={this.state.email}
            onChange={this.save("email")}
          />
          <br />
          <hr />
          <button onClick={this.login}>登录</button>
          <button onClick={this.reset}>重置</button>
        </form>
      </div>
    );
  }
}
